package com.spider.silence.output;

import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.UpdateResult;
import com.mongodb.gridfs.GridFS;
import com.spider.silence.itf.output.Writer;
import com.spider.silence.utils.DateUtils;
import com.spider.silence.utils.GridFsUtils;
import com.spider.silence.utils.SpringUtils;
import com.spider.silence.utils.ZipUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.springframework.context.ApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.io.File;
import java.util.*;
import java.util.zip.ZipEntry;

/**
 * @author 夏茂轩
 * @package com.spider.silence.output
 * @Date 2017/2/9 20:05
 */
public class MongoWriter implements Writer {
    ApplicationContext context = null;
    MongoTemplate template=null;
    @Override
    @Deprecated
    public boolean write(String path, String fileName, String content) throws Exception {
        try {
            if(context==null){
                context=SpringUtils.getContext();
            }
            template =context.getBean(MongoTemplate.class);
            DBCollection collection =template.getCollection("speeches");
            DBObject object = new BasicDBObject("_id",path+"/"+fileName).append("content",content).append("update_time", DateUtils.formatDateTime(new Date()));
            collection.save(object);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     *
     * @param path
     * @param fileName
     * @param content
     * @param files 单个帖子每一页的Html内容
     *                  key：帖子id
     *                  File:帖子的每一页文件
     * @return
     * @throws Exception
     */
    @Override
    public boolean write(String path, String fileName, String content, Map<String ,File> files) throws Exception {
        //帖子ID_pageNo_1
        //帖子的ID.zip
        try {
            if(context==null){
                context=SpringUtils.getContext();
            }
            template =context.getBean(MongoTemplate.class);
            DBCollection collection =template.getCollection("speeches");
            GridFS fs=new GridFS(template.getDb());
            File file=ZipUtils.ZipMultiFile(files,path+"_"+fileName); //压缩之后的文件
            DBObject object = new BasicDBObject("_id",path+"_"+fileName).append("content",content).append("update_time", DateUtils.formatDateTime(new Date()));
            collection.save(object);
            GridFsUtils.upload2GFS(file,fs);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public MongoWriter() {

    }
    public static void main(String[] args) {
        new MongoWriter();
    }
}
